﻿using GomokuCommon;
using System;
using System.Net.Sockets;

namespace GomokuServer {
    // 客户端
    class Client: Socket {
        public const int BUFFER_SIZE = 4096;    // 缓存长度
        private byte[] mBuffer;                 // 数据缓存
        private readonly Server mServer;        // 服务器

        /**
         * 构造方法。
         * @param si        套接字信息
         * @param server    服务器
         */
        public Client(SocketInformation si, Server server): 
            base(si) {
            mBuffer = new byte[BUFFER_SIZE];
            mServer = server;
            base.BeginReceive(mBuffer, 0, BUFFER_SIZE, 0, new AsyncCallback(OnReceive), this);
        }

        /**
         * 接收到数据的响应方法。
         * @param result    数据
         */
        public void OnReceive(IAsyncResult result) {
            // 接收数据
            int read = -1;
            try {
                read = base.EndReceive(result);
            } catch (Exception) {
                return;
            }
            if (read <= 0) {
                return;
            }

            // 将数据转换成协议
            GomokuProtocol pro = GomokuProtocol.FromBytes(mBuffer);

            // 处理协议
            mServer.OnGetMessageFromClient(pro, this);

            // 开始接收数据
            mBuffer = new byte[BUFFER_SIZE];
            try {
                base.BeginReceive(mBuffer, 0, BUFFER_SIZE, 0, new AsyncCallback(OnReceive), this);
            } catch (Exception) {
            }
        }
    }
}
